package com.tensquare.manager.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;

/**
 *
 */
@Component
public class ManagerFilter extends ZuulFilter {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public String filterType() {//过滤器类型
        return "pre";//前置过滤器
    }
    @Override
    public int filterOrder() {
        return 0;//优先级，数字越大，优先级越低
    }
    @Override
    public boolean shouldFilter() {
        return true;//过滤器开关，true表示开启
    }

    /**
     * 过滤器内执行的操作，return 任何Object的值都表示继续执行
     * setSendZuulResponse(false)表示不在执行
     *
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        System.out.println("Zuul后台过滤器");
        RequestContext requestContext=RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        //经过网关，有两次请求，第一次为网关内部的OPTIONS请求不带头信息负责找到路由的具体地址，第二次请求才携带请求头
        if(request.getMethod().equals("OPTIONS")){
            return null;
        }
        String url=request.getRequestURL().toString();
        //管理员登录，放行
        if(url.indexOf("/admin/login")>0){
            System.out.println("登陆页面"+url);
            return null;
        }
        String authHeader =(String)request.getHeader("Authorization");//获取头信息
        if(authHeader!=null && !authHeader.equals("") ){
            if(authHeader.startsWith("Bearer ")) {
                String token = authHeader.substring(7);
                try {
                    Claims claims = jwtUtil.parseJWT(token);
                    if ("admin".equals(claims.get("roles"))) {
                        //把头信息转发下去并且放行
                        requestContext.addZuulRequestHeader("Authorization", authHeader);
                        System.out.println("token 验证通过，添加了头信息" + authHeader);
                        return null;
                    }
                } catch (Exception e) {
                    requestContext.setSendZuulResponse(false);//终止运行
                    requestContext.setResponseStatusCode(401);//http状态码，权限不足
                    requestContext.setResponseBody("无权访问");
                    requestContext.getResponse().setContentType("text/html;charset=UTF-8");
                }
            }
        }
        requestContext.setSendZuulResponse(false);//终止运行
        requestContext.setResponseStatusCode(401);//http状态码，权限不足
        requestContext.setResponseBody("无权访问");
        requestContext.getResponse().setContentType("text/html;charset=UTF-8");
        return null;
    }
}
